package org.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.servlet.http.HttpServletResponse;

/**
* @description: TODO
* @author 杨镇宇
* @date 2024/7/12 16:01
* @version 1.0
*/

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**","/actuator/**").permitAll() // 允许匿名访问
                .antMatchers("/v3/**","/swagger-ui.html","/doc.html", "/webjars/**","/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs").permitAll() // 允许匿名访问 Swagger UI 和相关资源
                .anyRequest().authenticated()
                .and()
                .httpBasic() // 启用基本认证
                .and()
         .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    // 处理HTTPS调用失败后的拦截
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + authException.getMessage());
                });
    }
}